package com.jsgt.greekfire.common.widget

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.animation.ValueAnimator.AnimatorUpdateListener
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.LinearLayout
import androidx.annotation.Nullable
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.fhx.core.view.TabButton


class TabButtonContainer(
    context: Context?, @Nullable attrs: AttributeSet?,
    defStyleAttr: Int
) :
    LinearLayout(context, attrs, defStyleAttr), View.OnClickListener {
    private val mList: MutableList<TabButton>
    var mCurPosition: Int
    private val mAnimator: ValueAnimator?
    private var mAnimView: View? = null
    private val mRunnable: Runnable
    private var isLogin = false
    var fm: FragmentManager? = null
    var fragmentClassList: List<Class<*>>? = null
    var fragmentArr: Array<Fragment?>? = null
    var containerId: Int? = null
    var onTabSelectedListener: OnTabSelectedListener? = null

    constructor(context: Context?, @Nullable attrs: AttributeSet?) : this(context, attrs, 0)

    override fun onFinishInflate() {
        super.onFinishInflate()
        var i = 0
        val count = childCount
        while (i < count) {
            val v: View = getChildAt(i)
            v.tag = i
            v.setOnClickListener(this)
            mList.add(v as TabButton)
            i++
        }
    }

    fun setLoginState(login: Boolean) {
        this.isLogin = login
    }

    fun setUp(containerId: Int, fm: FragmentManager, list: List<Class<*>>) {
        fragmentClassList = list
        fragmentArr = arrayOfNulls(list.size)
        this.containerId = containerId
        this.fm = fm
    }

    override fun onClick(v: View) {
        val tag: Any = v.tag
        val position = tag as Int
        if (position == mCurPosition) {
            return
        }
        mList[mCurPosition].setChecked(false)
        val tbn = mList[position]
        tbn.setChecked(true)
        mCurPosition = position
        mAnimView = tbn
        mAnimator!!.start()
        postDelayed(mRunnable, 150)
    }


    fun resetState() {
        if (!mList.isNullOrEmpty()) {
            for (i in mList.indices) {
                mList[i].setChecked(false)
            }
            mList[0].setChecked(true)
            mCurPosition = 0
            postDelayed(mRunnable, 150)
        }
    }

    fun cancelAnim() {
        mAnimator?.cancel()
    }

    init {
        mList = ArrayList()
        mCurPosition = -1
        mAnimator = ValueAnimator.ofFloat(1.0f, 1.2f, 1f)
        mAnimator.addUpdateListener(AnimatorUpdateListener { animation ->
            val v = animation.animatedValue as Float
            if (mAnimView != null) {
                mAnimView?.scaleX = v
                mAnimView?.scaleY = v
            }
        })
        mAnimator.duration = 350
        mAnimator.interpolator = AccelerateDecelerateInterpolator()
        mAnimator.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator?) {
                mAnimView = null
            }
        })
        mRunnable = Runnable {
            val ft = fm?.beginTransaction()
            var instance = fragmentArr!![mCurPosition]
            var firstCreate = false
            if (instance == null) {
                firstCreate = true
                fragmentArr!![mCurPosition] =
                    fragmentClassList!![mCurPosition].newInstance() as Fragment?
                instance = fragmentArr!![mCurPosition]
                ft?.add(containerId!!, instance!!)
            }
            for (fragment in fragmentArr!!) {
                if (fragment != null) {
                    if (fragment === instance) {
                        if (!firstCreate) {
                            ft!!.show(fragment)
                        }
                    } else {
                        ft!!.hide(fragment)
                    }
                }
            }
            //这里不能用replace，会走onDestroy,而Fragment用了ViewModel来请求网络，一旦onDestroy之后，就发不了网络请求了
            ft?.commitAllowingStateLoss()
            if (firstCreate) {
                postDelayed(Runnable {
                    onTabSelectedListener?.onTabSelected(mCurPosition)
                },100)
            }else{
                onTabSelectedListener?.onTabSelected(mCurPosition)
            }
        }
    }

    var loginClick: (() -> Unit)? = null

    interface OnTabSelectedListener {
        fun onTabSelected(index: Int)
    }
}